package com.pengcheng.taskapplication.mvp.view.activity;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cpcn.cpcn_pay_sdk.CPCNPay;
import com.cpcn.cpcn_pay_sdk.PayResult;
import com.cpcn.cpcn_pay_sdk.ZhifubaoCallback;
import com.google.gson.Gson;
import com.pengcheng.taskapplication.R;
import com.pengcheng.taskapplication.contants.ConstantValue;
import com.pengcheng.taskapplication.model.ParkOrderModel;
import com.pengcheng.taskapplication.model.PayStatusModel;
import com.pengcheng.taskapplication.model.PayTypeModel;
import com.pengcheng.taskapplication.model.SortModel;
import com.pengcheng.taskapplication.model.WXEntity;
import com.pengcheng.taskapplication.model.WashOrderModel;
import com.pengcheng.taskapplication.model.WashTypeModel;
import com.pengcheng.taskapplication.mvp.presenter.UserPresenter;
import com.pengcheng.taskapplication.mvp.presenter.UserPresenterV2;
import com.pengcheng.taskapplication.mvp.view.fragment.DialogFragmentPayType;
import com.pengcheng.taskapplication.mvp.view.fragment.DialogFragmentWashType;
import com.pengcheng.taskapplication.mvp.view.fragment.InputPwdDialogFragment;
import com.pengcheng.taskapplication.mvp.view.fragment.ShowSettingDialogFragment;
import com.pengcheng.taskapplication.net.ConvertUtil;
import com.pengcheng.taskapplication.net.IView;
import com.pengcheng.taskapplication.util.Logger;
import com.pengcheng.taskapplication.util.SPUtils;
import com.pengcheng.taskapplication.util.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.w3c.dom.Text;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ZFT on 2020/10/28.
 */

public class WashConfrimOrderActivity extends BaseActivity implements IView,DialogFragmentPayType.OnFragmentInteractionListener,InputPwdDialogFragment.OnFragmentInteractionListener{

    @BindView(R.id.tv_center_title)
    TextView tv_center_title;

    @BindView(R.id.tv_u_name)
    TextView tv_u_name;

    @BindView(R.id.tv_u_car)
    TextView tv_u_car;

    @BindView(R.id.tv_tradno)
    TextView tv_tradno;

    @BindView(R.id.tv_wash_type)
    TextView tv_wash_type;

    private double money;


    //主要用于判断，微信支付和支付宝支付 -2微信 -1支付宝


    public String selectType;

    @BindView(R.id.tv_pay_fee)
    TextView tv_pay_fee;

    @BindView(R.id.ll_pay)
    LinearLayout ll_pay;

    @BindView(R.id.tv_pay_show)
    TextView tv_pay_show;

    @BindView(R.id.tv_finish_time)
    TextView tv_finish_time;

    private UserPresenterV2 userPresenter;
    private String uid;
    private String newtoken;
    private String tradno;
    private String deviceId;

    private IWXAPI iwxapi;

    private int from;

    private String ispwd;

    ArrayList<SortModel> list=new ArrayList<>();

    @Override
    protected int layoutResID() {
        return R.layout.activity_wash_confirm_order_layout;
    }

    @Override
    protected void initData() {
        from = getIntent().getIntExtra("from",0);
        iwxapi = WXAPIFactory.createWXAPI(this, ConstantValue.Wechat_Appid, true);
        iwxapi.registerApp(ConstantValue.Wechat_Appid);
        tv_center_title.setText("确认订单");
        userPresenter = new UserPresenterV2(this);
        uid=SPUtils.getString(context,ConstantValue.SpType.userid);
        newtoken=SPUtils.getString(context,ConstantValue.SpType.newtoken);
        tradno=getIntent().getStringExtra("tradno");
//        uid="60";
//        newtoken="1e454cd0ac2a6c97";
//        tradno="parking16077577872541722";
        getWashOrderDetail(newtoken,uid,tradno);
        getPaySort(newtoken,uid);
    }


    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        if(actionType.equals(ConstantValue.RequestKey.getOrderDetail)){
            WashOrderModel parkOrderModel=(WashOrderModel)data;
            if(parkOrderModel!=null){
                tv_u_name.setText(parkOrderModel.getCellphone());
                tv_u_car.setText(parkOrderModel.getCarnumber());
                tv_tradno.setText(parkOrderModel.getTradno());
                money=parkOrderModel.getMoney();
                BigDecimal bg = new BigDecimal(parkOrderModel.getMoney()/100);
                tv_pay_fee.setText("￥"+bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                deviceId=parkOrderModel.getDeviceid();
                tv_wash_type.setText(parkOrderModel.getWashtype().equals("finewash")?"精洗":"普通洗车");
                tv_finish_time.setText(ConvertUtil.getDateToString(parkOrderModel.getUpdatetime()));

                if(parkOrderModel.getStatus()==0){
                    ll_pay.setVisibility(View.VISIBLE);
                }else{
                    ll_pay.setVisibility(View.GONE);
                }
                if(parkOrderModel.getMoney()==0){
                    tv_pay_show.setText("完成支付");
                }else{
                    tv_pay_show.setText("去支付");
                }

            }
        }

        if(actionType.equals(ConstantValue.RequestKey.getOrderDetailStatus)){
            WashOrderModel parkOrderModel=(WashOrderModel)data;
            if(parkOrderModel!=null){
             int status=parkOrderModel.getStatus();
             if(status==2){
                 Intent intent =new Intent(context,PaySuccessActivity.class);
                 startActivity(intent);
                 WashConfrimOrderActivity.this.finish();

             }


            }
        }

        if (ConstantValue.RequestKey.wxpay.equals(actionType)) {

            WXEntity wxEntity = (WXEntity) data;
            //Logger.e("xuke", "wx=" + wxEntity.toString());
            PayReq request = new PayReq();
            PayTypeModel payTypeModel= new PayTypeModel();
            payTypeModel.type="wash";
            payTypeModel.extData=tradno;
            payTypeModel.extData2=deviceId;
            String param=new Gson().toJson(payTypeModel);
            request.extData=param;
            request.appId = wxEntity.getAppid();
            request.partnerId = wxEntity.getPartnerid();
            request.prepayId = wxEntity.getPrepayid();
            request.packageValue = wxEntity.getPackageX();
            request.nonceStr = wxEntity.getNoncestr();
            request.timeStamp = wxEntity.getTimestamp();
            request.sign = wxEntity.getPaySign();
            iwxapi.sendReq(request);
        }
        if (ConstantValue.RequestKey.notice.equals(actionType)) {
            Intent intent =new Intent(context,PaySuccessActivity.class);
            intent.putExtra("type","wash");
            startActivity(intent);
            WashConfrimOrderActivity.this.finish();
        }
        if(actionType.equals(ConstantValue.RequestKey.getPaySort)){
            PayStatusModel model=(PayStatusModel)data;
            if(model!=null){
                if(model.getPaywaylist()!=null){
                    list.clear();
                    list.addAll(model.getPaywaylist());
                }
                ispwd=model.ispwd;
            }

        }
        if (ConstantValue.RequestKey.cnpy.equals(actionType)) {
           ToastUtils.showShortToast(msg);
           //选择的是微信支付
           if(selectType.equals("-2")){
               CPCNPay.weixinPay(context,ConstantValue.Wechat_Appid,(String)data);
               WashConfrimOrderActivity.this.finish();
               //选择的支付宝支付
           }else if(selectType.equals("-1")){
               CPCNPay.zhifubaoPay(WashConfrimOrderActivity.this, (String) data, zhifubaoCallback);
           }

        }




    }

    ZhifubaoCallback zhifubaoCallback= new ZhifubaoCallback() {
        @Override
        public void onResult(PayResult payResult) {
            if(payResult.getResultStatus().equals("9000")){
                //成功
                Intent intent =new Intent(context,PaySuccessActivity.class);
                startActivity(intent);
                WashConfrimOrderActivity.this.finish();


            }else{
                //失败
                ToastUtils.showShortToast("支付失败，请重试");
            }
        }
    };

    @Override
    public void onFailed(String code, String msg) {

    }

    @OnClick({R.id.img_back,R.id.img_show,R.id.ll_pay})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.ll_pay:
                //拉取支付预支付信息
                if(tv_pay_show.getText().toString().equals("去支付")) {
                   // wxpay(newtoken, uid, tradno);
                    showDialog(list);

                }else if(tv_pay_show.getText().toString().equals("完成支付")){
                    notice(newtoken,uid,tradno);
                }
                break;
        }
    }
    public  void wxpay(String token,String uid,String tradno){
        userPresenter.wxwashpay(token,uid,tradno,ConstantValue.RequestKey.wxpay);
    }

    public  void getWashOrderDetail(String token,String uid,String tradno){
        userPresenter.getWashOrderDetail(token,uid,tradno,ConstantValue.RequestKey.getOrderDetail);
    }

    public  void getWashOrderDetailStatus(String token,String uid,String tradno){
        userPresenter.getWashOrderDetail(token,uid,tradno,ConstantValue.RequestKey.getOrderDetailStatus);
    }

    public  void notice(String token,String uid,String tradno){
        userPresenter.notice(token,uid,tradno,ConstantValue.RequestKey.notice);
    }



    void showDialog(ArrayList<SortModel> sortModels) {

//        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//        Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog2");
//        if (prev != null) {
//            ft.remove(prev);
//        }
//        ft.addToBackStack(null);
//
//        // Create and show the dialog.
//        DialogFragmentPayType newFragment = DialogFragmentPayType.newInstance(sortModels);
//        newFragment.show(ft, "dialog2");

        FragmentManager fm = getSupportFragmentManager();
        DialogFragmentPayType dialogFragmentPayType =  DialogFragmentPayType.newInstance(sortModels);
        dialogFragmentPayType.show(fm, "fragment_bottom_dialog");
//        dialogFragmentPayType.showNow(fm, "fragment_bottom_dialog");
    }


    public void showBottomDialog(View view) {

    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onDelete() {

    }

    @Override
    public void onCompete(SortModel sortModel) {
        //当前选中支付方式
        //该支付方式需要密码
        if(ispwd!=null) {
            if (ispwd.equals("1")) {
                //需要密码  ,弹出输入密码的窗口
                selectType=sortModel.id;
                showInputPwdDialog(sortModel,money);

            } else {
                //不需要密码
                selectType=sortModel.id;
                cpcnpay(newtoken, uid, tradno, sortModel.getId(), null);
            }
        }


    }
    public void getPaySort(String token,String uid){
        userPresenter.getPaySort(token,uid,"0", ConstantValue.RequestKey.getPaySort);
    }


    public void cpcnpay(String token,String uid,String tradno,String payway,String paypwd){
        userPresenter.cpcnpay(token,uid,tradno,payway,paypwd, ConstantValue.RequestKey.cnpy);
    }


    void showInputPwdDialog(SortModel sortModel,double money) {

//        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//        Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
//        if (prev != null) {
//            ft.remove(prev);
//        }
//        ft.addToBackStack(null);

        // Create and show the dialog.
        FragmentManager fm = getSupportFragmentManager();
        InputPwdDialogFragment newFragment = InputPwdDialogFragment.newInstance(sortModel,money);
        newFragment.show(fm, "dialog");
//        newFragment.showNow(fm, "dialog");
    }


    @Override
    public void onConfirm(String pwd) {
        cpcnpay(newtoken, uid, tradno, selectType, pwd);
    }

    @Override
    public void checkPayType() {
        //修改支付方式，需要再次调起来弹窗
        showDialog(list);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getWashOrderDetailStatus(newtoken,uid,tradno);
    }
}
